"""
扫描记录价格分析管理模块
"""
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any
from sqlalchemy import and_, or_
from com.db.models import ScanRecordPriceAnalysis, get_session
from com.utils.logger import get_logger

logger = get_logger("ScanRecordPriceAnalysisManager")

class ScanRecordPriceAnalysisManager:
    """扫描记录价格分析管理器"""
    
    @staticmethod
    def add_analysis(analysis_data: Dict[str, Any]) -> bool:
        """
        添加或更新价格分析记录。
        使用商品ID和分析日期作为唯一键，如果当天已有记录则更新，否则新增。
        analysis_period格式为YYYYMMDD，例如：20250220
        
        Args:
            analysis_data: 分析数据字典
            
        Returns:
            bool: 是否添加/更新成功
        """
        try:
            session = get_session()
            
            # 设置analysis_period为当前日期的YYYYMMDD格式
            analysis_date = analysis_data['analysis_time'].date()
            analysis_data['analysis_period'] = analysis_date.strftime('%Y%m%d')
            
            # 过滤掉不存在于ScanRecordPriceAnalysis模型中的字段
            valid_fields = [column.key for column in ScanRecordPriceAnalysis.__table__.columns]
            filtered_data = {k: v for k, v in analysis_data.items() if k in valid_fields}
            
            # 查找是否存在同一商品同一天的记录
            existing = session.query(ScanRecordPriceAnalysis).filter(
                and_(
                    ScanRecordPriceAnalysis.goods_id == filtered_data['goods_id'],
                    ScanRecordPriceAnalysis.analysis_period == filtered_data['analysis_period']
                )
            ).first()
            
            if existing:
                # 更新现有记录
                for key, value in filtered_data.items():
                    setattr(existing, key, value)
                logger.info(f"更新价格分析记录: 商品ID={filtered_data['goods_id']}, 日期={filtered_data['analysis_period']}")
            else:
                # 添加新记录
                analysis = ScanRecordPriceAnalysis(**filtered_data)
                session.add(analysis)
                logger.info(f"添加新价格分析记录: 商品ID={filtered_data['goods_id']}, 日期={filtered_data['analysis_period']}")
            
            session.commit()
            return True
        except Exception as e:
            logger.error(f"添加/更新价格分析记录失败: {str(e)}", exc_info=True)
            session.rollback()
            return False
        finally:
            session.close()
    
    @staticmethod
    def get_latest_analysis(goods_id: int, period: str = '24h') -> Optional[Dict[str, Any]]:
        """
        获取商品最新的价格分析记录
        
        Args:
            goods_id: 商品ID
            period: 分析周期，默认24h
            
        Returns:
            Optional[Dict]: 分析记录字典，如果不存在返回None
        """
        try:
            session = get_session()
            
            # 检查表中是否有数据
            # total_count = session.query(ScanRecordPriceAnalysis).count()
            # logger.info(f"ScanRecordPriceAnalysis 表中总共有 {total_count} 条记录")
            
            # 获取所有商品ID
            all_goods_ids = session.query(ScanRecordPriceAnalysis.goods_id).distinct().all()
            logger.info(f"表中存在的商品ID: {[gid[0] for gid in all_goods_ids]}")
            
            # 获取最新的分析记录，不再限制analysis_period
            analysis = session.query(ScanRecordPriceAnalysis).filter(
                ScanRecordPriceAnalysis.goods_id == goods_id
            ).order_by(ScanRecordPriceAnalysis.analysis_time.desc()).first()
            
            if analysis:
                logger.info(f"找到商品 {goods_id} 的最新分析记录，时间：{analysis.analysis_time}")
                return {
                    'id': analysis.id,
                    'goods_id': analysis.goods_id,
                    'goods_name': analysis.goods_name,
                    'hash_name': analysis.hash_name,
                    'wear': analysis.wear,
                    'exterior': analysis.exterior,
                    'rarity': analysis.rarity,
                    'quality': analysis.quality,
                    'analysis_time': analysis.analysis_time,
                    'analysis_period': analysis.analysis_period,
                    'price_variance': analysis.price_variance,
                    'abnormal_prices': analysis.abnormal_prices,
                    'common_sell_price': analysis.common_sell_price,
                    'historical_low': analysis.historical_low,
                    'price_distribution': analysis.price_distribution,
                    'selling_count': analysis.selling_count,
                    'normal_price': analysis.normal_price,
                    'scan_reference_price': analysis.scan_reference_price
                }
            logger.warning(f"未找到商品 {goods_id} 的分析记录")
            return None
        except Exception as e:
            logger.error(f"获取最新价格分析记录失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return None
        finally:
            session.close()
    
    @staticmethod
    def update_analysis(analysis_id: int, update_data: Dict[str, Any]) -> bool:
        """
        更新价格分析记录
        
        Args:
            analysis_id: 分析记录ID
            update_data: 更新数据字典
            
        Returns:
            bool: 是否更新成功
        """
        try:
            session = get_session()
            analysis = session.query(ScanRecordPriceAnalysis).filter(
                ScanRecordPriceAnalysis.id == analysis_id
            ).first()
            
            if not analysis:
                return False
                
            for key, value in update_data.items():
                if hasattr(analysis, key):
                    setattr(analysis, key, value)
            
            analysis.update_at = datetime.now()
            session.commit()
            return True
        except Exception as e:
            logger.error(f"更新价格分析记录失败: {str(e)}")
            session.rollback()
            return False
        finally:
            session.close()
    
    @staticmethod
    def get_analysis_history(goods_id: int, days: int = 7) -> List[Dict[str, Any]]:
        """
        获取商品的历史价格分析记录
        
        Args:
            goods_id: 商品ID
            days: 获取最近几天的记录，默认7天
            
        Returns:
            List[Dict]: 分析记录列表
        """
        try:
            session = get_session()
            start_date = datetime.now() - timedelta(days=days)
            
            analyses = session.query(ScanRecordPriceAnalysis).filter(
                and_(
                    ScanRecordPriceAnalysis.goods_id == goods_id,
                    ScanRecordPriceAnalysis.analysis_time >= start_date
                )
            ).order_by(ScanRecordPriceAnalysis.analysis_time.desc()).all()
            
            return [{
                'id': analysis.id,
                'goods_id': analysis.goods_id,
                'goods_name': analysis.goods_name,
                'analysis_time': analysis.analysis_time,
                'analysis_period': analysis.analysis_period,
                'price_variance': analysis.price_variance,
                'common_sell_price': analysis.common_sell_price,
                'historical_low': analysis.historical_low
            } for analysis in analyses]
        except Exception as e:
            logger.error(f"获取价格分析历史记录失败: {str(e)}")
            return []
        finally:
            session.close()

    @staticmethod
    def get_analysis_history_all(goods_id: int) -> List[Dict[str, Any]]:
        """
        获取指定商品的历史分析数据
        
        Args:
            goods_id: 商品ID
            
        Returns:
            List[Dict]: 历史分析数据列表，按时间倒序排序
        """
        try:
            session = get_session()
            records = (
                session.query(ScanRecordPriceAnalysis)
                .filter(ScanRecordPriceAnalysis.goods_id == goods_id)
                .order_by(ScanRecordPriceAnalysis.analysis_time.desc())
                .all()
            )
            
            return [{
                'id': record.id,
                'goods_id': record.goods_id,
                'goods_name': record.goods_name,
                'hash_name': record.hash_name,
                'wear': record.wear,
                'exterior': record.exterior,
                'rarity': record.rarity,
                'quality': record.quality,
                'analysis_time': record.analysis_time,
                'analysis_period': record.analysis_period,
                'price_variance': record.price_variance,
                'abnormal_prices': record.abnormal_prices,
                'common_sell_price': record.common_sell_price,
                'historical_low': record.historical_low,
                'price_distribution': record.price_distribution,
                'selling_count': record.selling_count,
                'normal_price': record.normal_price
            } for record in records]
            
        except Exception as e:
            logger.error(f"获取商品 {goods_id} 的历史分析数据失败: {str(e)}")
            return []
            
        finally:
            session.close()
